﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using GoogleMobileAds.Api;


public class User : MonoBehaviour
{
    public static User instance;

    private int money;
    private bool haveSign;
    private bool canSign;
    private int dateOfSign;
    private int dateOfToday;
    private int daysOfSign;
    private int skinsHadNum = 1;
    private readonly int skinsAllNum = 9;
    private int curLevel;
    private readonly int maxLevel = 29;

    //private GameObject player;

    public bool moneyBool;
    public bool skinBool;
    public bool luckyBool;
    public bool skipBool;
    /// <summary>
    /// 当前被选中的皮肤
    /// </summary>
    public CharacterInfo skinOnSwitch;


    public List<SkinClass> skinList;
    public List<SkinClass> levelSkinList;
    private int levelSkinIndex = 0;

    //public SkinClass curSkin;

    /// <summary>
    /// 是否已签到
    /// </summary>
    public bool HaveSign { get => haveSign; set => haveSign = value; }
    /// <summary>
    /// 是否可签到
    /// </summary>
    public bool CanSign { get => canSign; set => canSign = value; }
    /// <summary>
    /// 已签到天数
    /// </summary>
    public int DaysOfSign { get => daysOfSign; set => daysOfSign = value; }
    /// <summary>
    /// 上次签到日期
    /// </summary>
    public int DateOfSign { get => dateOfSign; set => dateOfSign = value; }
    /// <summary>
    /// 今天日期(365天中的第几天)
    /// </summary>
    public int DateOfToday { get => dateOfToday; set => dateOfToday = value; }
    /// <summary>
    /// 用户金币数
    /// </summary>
    public int Money { get => money; }
    /// <summary>
    /// 拥有的皮肤数
    /// </summary>
    public int SkinsHadNum { get => skinsHadNum; set => skinsHadNum = value; }
    /// <summary>
    /// 可供解锁的皮肤数
    /// </summary>
    public int SkinsAllNum { get => skinsAllNum;}
    /// <summary>
    /// 当前已完成的关卡
    /// </summary>
    public int CurLevel { get => curLevel; set => curLevel = value; }
    /// <summary>
    /// 最高关卡
    /// </summary>
    public int MaxLevel => maxLevel;


    //public GameObject Player { get => player; set => player = value; }

    private void Awake()
    {
        if (instance != null)
        {
            Destroy(this);
        }
        instance = this;

        DataRead();
        UserSign();

        //BannerView bannerView = new BannerView(bannerAdId, AdSize.Banner, AdPosition.Bottom);
        //AdRequest request = new AdRequest.Builder().Build();
        //bannerView.LoadAd(request);
    }

    /// <summary>
    /// 更改金币数（带正负）
    /// </summary>
    /// <param name="num"></param>
    public void ChangeMoney(int num)
    {
        money = Mathf.Clamp(money + num, 0, 99999);
        PlayerPrefs.SetInt("money", Money);

        GameObject panel_main = GameObject.Find("Panel_Main(Clone)");
        if (panel_main)
        {
            panel_main.GetComponent<Panel_Main>().ShowTextMoney();
        }

        GameObject panel_skin = GameObject.Find("Panel_Character(Clone)");
        if (panel_skin)
        {
            panel_skin.GetComponent<Panel_Character>().UpdatePanelData();
        }
    }

    /// <summary>
    /// 过关，关卡加一，获得金币（特定关卡后，解锁新皮肤）
    /// </summary>
    public void ThroughLevel()
    {
        int num = (CurLevel / 10 + 1) * 100;
        ChangeMoney(num);
        CurLevel++;
        PlayerPrefs.SetInt("CurLevel", CurLevel);
        //Debug.LogError(levelSkinList.Count);

        if (CurLevel == levelSkinList[levelSkinIndex].levelNeed)
        {
            levelSkinList[levelSkinIndex].haveGot = true;
            User.instance.SkinsHadNum++;

            levelSkinIndex = Mathf.Clamp(levelSkinIndex++, 0, levelSkinList.Count - 1);
            PlayerPrefs.SetInt("levelSkinIndex", levelSkinIndex);
        }
    }

    /// <summary>
    /// 判断用户是否签到，是否能签到
    /// </summary>
    public void UserSign()
    {
        if (DateOfSign != DateOfToday)
        {
            CanSign = true;
            HaveSign = false;
        }
        else
        {
            CanSign = false;
            HaveSign = true;
        }
        //Debug.Log(CanSign);

        if (canSign && daysOfSign == 7)
        {
            daysOfSign = 0;
        }
    }

    /// <summary>
    /// 皮肤数据存储
    /// </summary>
    public void SkinDataSave()
    {
        PlayerPrefs.SetInt("SkinsHadNum", SkinsHadNum);

        Debug.Log(Application.persistentDataPath);
        if (!Directory.Exists(Application.persistentDataPath + "/GameData"))
        {
            Directory.CreateDirectory(Application.persistentDataPath + "/GameData");
        }

        BinaryFormatter formatter = new BinaryFormatter();          //为实现二进制转化

        for (int i = 0; i < skinList.Count; i++)
        {
            FileStream file = File.Create(Application.persistentDataPath + "/GameData/" + skinList[i].skinName);

            var json = JsonUtility.ToJson(skinList[i]);
            formatter.Serialize(file, json);
            file.Close();
        }
    }
    /// <summary>
    /// 读取数据
    /// </summary>
    public void DataRead()
    {
        Debug.Log("read");

        DateOfToday = System.DateTime.Now.DayOfYear;
        money = PlayerPrefs.GetInt("money", 0);
        DaysOfSign = PlayerPrefs.GetInt("DaysOfSign", 0);
        DateOfSign = PlayerPrefs.GetInt("DateOfSign", 0);
        CurLevel = PlayerPrefs.GetInt("CurLevel", 0);
        levelSkinIndex = PlayerPrefs.GetInt("levelSkinIndex", 0);
        SkinsHadNum = PlayerPrefs.GetInt("SkinsHadNum", 1);

        for (int i = 0; i < skinList.Count; i++)
        {
            if (File.Exists(Application.persistentDataPath + "/GameData/" + skinList[i].skinName))
            {
                BinaryFormatter bf = new BinaryFormatter();

                FileStream file = File.OpenRead(Application.persistentDataPath + "/GameData/" + skinList[i].skinName);

                JsonUtility.FromJsonOverwrite((string)bf.Deserialize(file), skinList[i]);

                file.Close();
            }
        }

    }


}
